// 网络请求工具

import axios from 'axios';
import { ElMessage } from 'element-plus';

const service = axios.create({
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  }
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    const whiteList = ['/auth/login', '/auth/register'];

    if (token && !whiteList.includes(config.url || '')) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    console.error('请求错误:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const { data } = response;
    if (response.status === 200) {
      return response;
    }
    ElMessage.error(data.message || '请求失败');
    return Promise.reject(data);
  },
  (error) => {
    console.error('响应错误:', error);
    ElMessage.error(error.message || '服务器错误');
    return Promise.reject(error);
  }
);

/**
 * 封装请求方法
 * @param options 请求配置
 * @returns Promise
 */
export const axiosRequest = <T = any>(options: RequestOptions): Promise<T> => {
  const { url, method = 'POST', data, params, ...config } = options;
  return service({
    url,
    method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: method.toUpperCase() === 'GET' ? params : data,
    ...config
  }) as Promise<T>;
};
